import Vue from 'vue'
import VueRouter from 'vue-router'
import Cookies from 'js-cookie'

Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  //引用路由 
  {
    path: '/',
    redirect: '/index'
  },
  {
    path: '/index', //新闻首页
    name: 'index',
    component: () => import('../views/index/index.vue'),
  },
  {
    path: '/login', //登录页
    name: 'login',
    component: () => import('../views/login/index.vue'),
  }
]

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  if(Cookies.get('store')){
    let token=JSON.parse(Cookies.get('store')).token;
  }else{
    next();
  }
  if (to.name == 'login') {
    next();
    return;
  }
  if(to.meta.requireAuth&&!token){
    next({path:'/login',query:{redirect:to.fullPath}})
  }else{
    next();
  }

})
export default router
